package helper;

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;

public class HttpHandler
{
	private HttpConnection httpConnection;
	private DataInputStream dis;
	private StringBuffer sb;
	private byte[] byteBuffer;
	             
	public HttpHandler()
	{
		this.httpConnection = null;
		this.dis = null;
		this.sb = new StringBuffer();
		this.byteBuffer = null;
	}
	
	public String httpGet(String url)
	{
		try
		{
			this.httpConnection = (HttpConnection) Connector.open(url);
			this.dis = new DataInputStream(this.httpConnection.openInputStream());
		
			int ch;

	        while ( (ch = dis.read()) != -1 ) 
	        	this.sb = this.sb.append((char) ch);

		}
		catch(Exception e)
		{ 
			System.out.println("Erro ao ler stream.");
			e.printStackTrace(); 
		}
		finally 
		{
			try
			{
				if(this.httpConnection != null ) this.httpConnection.close();
				if ( this.dis != null ) this.dis.close();
			} catch (IOException e)
			{
				System.out.println("Erro ao encerrar conexao.");
				e.printStackTrace();
			}
		}
	     
		return this.sb.toString();

	}

	public Image httpGetImage(String url)
	{
		try
		{
			this.httpConnection = (HttpConnection) Connector.open(url);
			this.dis = new DataInputStream(this.httpConnection.openInputStream());
		
			int length; 
			length = (int) this.httpConnection.getLength();
			
			if(length <= 0)
				return null;
			
			this.byteBuffer = new byte[length];
			this.dis.readFully(this.byteBuffer);

		}
		catch(Exception e)
		{ 
			System.out.println("Erro ao ler stream.");
			e.printStackTrace(); 
		}
		finally 
		{
			try
			{
				if(this.httpConnection != null ) this.httpConnection.close();
				if ( this.dis != null ) this.dis.close();
			} catch (IOException e)
			{
				System.out.println("Erro ao encerrar conexao.");
				e.printStackTrace();
			}
		}
	     
		return Image.createImage(this.byteBuffer, 0,this.byteBuffer.length);

	}
}
